#ifndef __OJ_VIEW_HPP__
#define __OJ_VIEW_HPP__
// OJ题目渲染网页
#include <iostream>
#include <vector>
#include <ctemplate/template.h>

// #include "oj_model_file.hpp"
#include "oj_model_mysql.hpp"


namespace ns_view
{
    using namespace ns_model;

    class View
    {
        const std::string template_path = "./template_html/";

        std::string color_class_for_star(const std::string& star) {
            if (star == "简单") {
                return "color-easy";
            } else if (star == "中等") {
                return "color-moderate";
            } else if (star == "困难") {
                return "color-hard";
            } else {
                return "color-black";
            }
        }
    public:
        View(){}
        ~View(){}
        // 渲染题目列表网页
        // 保存题目列表的数组 + 待返回的渲染网页
        void AllExpandHtml(const std::vector<Question>& questions, std::string& html)
        {
            // 1.模板网页路径
            std::string path = template_path + "all_questions.html";
            // 2.形成数据字典
            ctemplate::TemplateDictionary root("all_questions");
            // 循环渲染一部分网页表格，设定子字典
            for (auto& q : questions)
            {
                ctemplate::TemplateDictionary* td = root.AddSectionDictionary("question_list");  // 在模板网页中需要{{#名字}}
                td->SetValue("number", q.number);
                td->SetValue("title", q.title);
                td->SetValue("star", q.star);
                td->SetValue("star_color_class", color_class_for_star(q.star));
            }

            // 3.获取待渲染网页
            ctemplate::Template* tql = ctemplate::Template::GetTemplate(path, ctemplate::DO_NOT_STRIP);

            // 4.渲染网页返回
            tql->Expand(&html, &root);
        }

        // 渲染单题目网页
        // 单题目数据结构 + 待返回的渲染网页
        void OneExpandHtml(const Question& q, std::string& html)
        {
            std::string path = template_path + "one_question.html";
            ctemplate::TemplateDictionary root("one_question");

            root.SetValue("number", q.number);
            root.SetValue("title", q.title);
            root.SetValue("star", q.star);
            std::string str = std::to_string((q.cpu_commit * 1.0));
            root.SetValue("cpu", str.substr(0, str.find(".") + 3));
            str = std::to_string(q.mem_commit * 1.0 / 1024);
            root.SetValue("mem", str.substr(0, str.find(".") + 3));
            root.SetValue("desc", q.desc);
            root.SetValue("pre_code", q.header);

            ctemplate::Template* tql = ctemplate::Template::GetTemplate(path, ctemplate::DO_NOT_STRIP);
            tql->Expand(&html, &root);
        }

	void AdminPageHtml(std::string& html) {
        	std::string path = template_path + "admin.html";
        	std::ifstream file(path);
        	html = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
    	}
    };
}

#endif
